package com.zengdada.authority.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    private final List<PropertySourceLoader> propertySourceLoaders;

    public MyEnvironmentPostProcessor() {
        super();
        this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
    }

    //    activeProfiles
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String[] activeProfiles = environment.getActiveProfiles();
        List<String> actives = Arrays.stream(activeProfiles).collect(Collectors.toList());
        actives.add("default");
        actives.add(0, "config");
        for (String activeProfile : actives) {
            for (PropertySourceLoader loader : this.propertySourceLoaders) {
                for (String fileExtension : loader.getFileExtensions()) {
                    String location = ("default".equals(activeProfile) || "config".equals(activeProfile) ? "classpath:/" : "classpath:/environment/") + activeProfile + "/*." + fileExtension;
                    try {
                        Resource[] resources = this.resourcePatternResolver.getResources(location);
                        for (Resource resource : resources) {
                            List<PropertySource<?>> propertySources = loader.load(resource.getFilename(), resource);
                            if (null != propertySources && !propertySources.isEmpty()) {
                                propertySources.forEach(environment.getPropertySources()::addLast);
                            }
                        }
                    } catch (IOException e) {
//                        e.printStackTrace();
                        log.error("配置文件加载失败：" + e.getMessage());
                        System.err.println("配置文件加载失败：" + e.getMessage());
                    }
                }
            }
        }
        if (!isHaveByName(environment.getPropertySources(), "authority.application.id")) {
            log.error("authority.application.id 没有配置或者为空！！");
            System.err.println("启动失败： authority.application.id 没有配置或者为空！！");
            System.exit(0);
        }
    }

    public boolean isHaveByName(MutablePropertySources sources, String name) {
        for (PropertySource<?> propertySource : sources) {
            if (propertySource.getProperty(name) != null)
                return true;
        }
        return false;
    }
}
